package com.chhuang.system.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.service.impl.BaseServiceImpl;
import com.chhuang.system.bean.ChRoleQueryBean;
import com.chhuang.system.mapper.ChRoleMapper;
import com.chhuang.system.po.ChRole;
import com.chhuang.system.po.ChRoleExample;
import com.chhuang.system.service.IChRoleService;
import com.chhuang.utils.Assert;

/**
* ChRole ServiceImpl
* @author ChHuang
* @date Fri Mar 03 13:20:59 CST 2017
*/
@Service
public class ChRoleServiceImpl extends BaseServiceImpl<ChRoleMapper, ChRole> implements IChRoleService {
	@Autowired
	private ChRoleMapper chRoleMapper;

	@Override
	public QueryBean<ChRole> seniorQuery(QueryBean<ChRole> queryBean) throws Exception {
		ChRoleQueryBean poQueryBean = (ChRoleQueryBean)queryBean;
		ChRoleExample example = new ChRoleExample();
		
		if(poQueryBean.isAnd()){//全部是与条件
			ChRoleExample.Criteria criteria= example.createCriteria();
			if(Assert.isValidString(poQueryBean.getRoleName())){
				criteria.andRoleNameLike("%"+poQueryBean.getRoleName()+"%");
			}
		}else{//全部是或条件
			if(Assert.isValidString(poQueryBean.getRoleName())){
				example.or().andRoleNameLike("%"+poQueryBean.getRoleName()+"%");
			}
		}
		
		poQueryBean.setItemCount(chRoleMapper.countByExample(example));//总记录数
		if(poQueryBean.getItemCount()>0){//计算总页数
			poQueryBean.setPageCount(poQueryBean.getItemCount()/poQueryBean.getPageSize()+
					(int)(poQueryBean.getItemCount()%poQueryBean.getPageSize()>0?1:0));
			if(poQueryBean.getPageCount()>=poQueryBean.getPageNum()){
				if(Assert.isValidString(poQueryBean.getOrderBy())){//排序
					example.setOrderByClause(poQueryBean.getOrderBy()+" "+poQueryBean.getOrder());
				}
				//分页
				example.setOffset((poQueryBean.getPageNum()-1)*poQueryBean.getPageSize());
				example.setLimit(poQueryBean.getPageSize());
				poQueryBean.setResult(chRoleMapper.selectByExample(example));
			}
		}
		
		return poQueryBean;
	}

	@Override
	public List<ChRole> findAllRoles() throws Exception {
		ChRoleExample example = new ChRoleExample();
		example.setOrderByClause("role_order asc");
		return chRoleMapper.selectByExample(example);
	}

	@Override
	public int deleteByRoleIdArray(String[] roleIds) throws Exception {
		ChRoleExample example = new ChRoleExample();
		example.createCriteria().andRoleIdIn(Arrays.asList(roleIds));
		return chRoleMapper.deleteByExample(example);
	}

	@Override
	public List<ChRole> findByRoleIds(String[] roleIds) throws Exception {
		ChRoleExample example = new ChRoleExample();
		example.createCriteria().andRoleIdIn(Arrays.asList(roleIds));
		example.setOrderByClause("role_order asc");
		return chRoleMapper.selectByExample(example);
	}

}